/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tencent.tendon.convert.json.listeners;

import com.tencent.tendon.convert.json.JsonReader;
import com.tencent.tendon.convert.json.JsonWriter;

/**
 *
 * @author nbzhang
 */
public final class JsonDoubleArrayListener extends JsonAbstractListener<double[]> {

    private static final JsonDoubleArrayListener instance = new JsonDoubleArrayListener();

    private static final JsonDoubleListener listener = JsonDoubleListener.getInstance();

    private JsonDoubleArrayListener() {
    }

    public static JsonDoubleArrayListener getInstance() {
        return instance;
    }

    @Override
    public double[] convertFrom(final JsonReader in) {
        int size = 0;
        double[] data = new double[8];
        in.checkArray();
        while (in.hasNext()) {
            if (size >= data.length) {
                double[] newdata = new double[data.length + 4];
                System.arraycopy(data, 0, newdata, 0, size);
                data = newdata;
            }
            data[size++] = listener.convertDoubleFrom(in);
        }
        double[] newdata = new double[size];
        System.arraycopy(data, 0, newdata, 0, size);
        return newdata;
    }

    @Override
    public final void convertTo(final JsonWriter out, final double[] value) {
        double[] values = value;
        if (values == null) {
            out.writeNull();
            return;
        }
        if (values.length == 0) {
            out.write('[', ']');
            return;
        }

        out.write('[');
        boolean first = true;
        for (double v : values) {
            if (!first) out.write(',');
            listener.convertDoubleTo(out, v);
            if (first) first = false;
        }
        out.write(']');
    }

    @Override
    public Class<double[]> getType() {
        return double[].class;
    }

    @Override
    public String toString() {
        return this.getClass().getSimpleName();
    }
}